package com.easyfun.healthmagicbox;


import java.sql.SQLException;

import cn.sharesdk.onekeyshare.OnekeyShare;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.RemovePersonProfileTask;
import com.easyfun.healthmagicbox.comm.ShareByInviteCodeTask;
import com.easyfun.healthmagicbox.comm.UserToPersonsDownloadTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DoctorAndSuggestion;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.HealthService;
import com.easyfun.healthmagicbox.sync.SyncUtility;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.widget.ProfileImageView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.easyfun.healthmagicbox.widget.DialogBuilder;

import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

public class HMBMainActivity extends BaseActivity implements DatabaseAccess{
	protected static final String TAG = HMBMainActivity.class.getSimpleName();
	private GridView gridView;
	private static ImageAdapter myimageadapter = null;

	private boolean fastUImode = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hmbmain);
		
		//addbackButton should after setting content view
		addbackButton(this);
		//String m_username = getIntent().getStringExtra(ConstantData.HMBUSERNAME);
		String m_username = PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this);
		if ((m_username == null) || (m_username.length() == 0)) {
			setResult(RESULT_CANCELED);
			finish();
			return;
		}		
		
		//String m_personID = getIntent().getStringExtra(ConstantData.HMBPERSONID);

		String m_personID = PersonProfileCache.getInstance(HMBMainActivity.this).getPersonID(HMBMainActivity.this);
		if ((m_personID == null) || (m_personID.length() == 0)) {
			setResult(RESULT_CANCELED);
			finish();
			return;
		}		
		
		myimageadapter = ImageAdapter.getInstance(this);
		setupView();
		OnClickListener clicklistener = new OnClickListener() {			
			@Override
			public void onClick(View v) {
				final Intent intent = new Intent(HMBMainActivity.this, SettingActivity.class);	        	
				HMBMainActivity.this.startActivity(intent);//
			}
		};
		RelativeLayout rightpress = (RelativeLayout) findViewById(R.id.rightpress);
		if (rightpress != null)
			rightpress.setOnClickListener(clicklistener);
		ImageButton settingButton = (ImageButton) findViewById(R.id.title_setting_btn);
		settingButton.setOnClickListener(clicklistener);
		
		Button shareButton = (Button) findViewById(R.id.btn_shareapp);	
		
		shareButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try
				{
					OnekeyShare oks = new OnekeyShare();
	
					// 分享时Notification的图标和文字
					oks.setNotification(R.drawable.ic_launcher,
					HMBMainActivity.this.getString(R.string.app_name));
					// address是接收人地址，仅在信息和邮件使用
					//oks.setAddress("12345678901");
					// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
					oks.setTitle(HMBMainActivity.this.getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					//oks.setTitleUrl("http://sharesdk.cn");
					// text是分享文本，所有平台都需要这个字段
					oks.setText("推荐大家使用家庭健康宝盒，这个app. http://www.kangbox.cn");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					//oks.setImagePath(MainActivity.TEST_IMAGE);
					// imageUrl是图片的网络路径，新浪微博、人人网、QQ空间、
					// 微信的两个平台、Linked-In支持此字段
					oks.setImageUrl("http://www.kangbox.cn/cakephp/images/hblogo72.png");
					// url仅在微信（包括好友和朋友圈）中使用
					oks.setUrl("http://www.kangbox.cn/cakephp/download.php");
					// appPath是待分享应用程序的本地路劲，仅在微信中使用
					//oks.setAppPath(MainActivity.TEST_IMAGE);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					//oks.setComment(getContext().getString(R.string.share));
					// site是分享此内容的网站名称，仅在QQ空间使用
					//oks.setSite(context.getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					//oks.setSiteUrl("http://sharesdk.cn");
					// venueName是分享社区名称，仅在Foursquare使用
					//oks.setVenueName("Southeast in China");
					// venueDescription是分享社区描述，仅在Foursquare使用
					//oks.setVenueDescription("This is a beautiful place!");
					// latitude是维度数据，仅在新浪微博、腾讯微博和Foursquare使用
					//oks.setLatitude(23.122619f);
					// longitude是经度数据，仅在新浪微博、腾讯微博和Foursquare使用
					//oks.setLongitude(113.372338f);
					// 是否直接分享（true则直接分享）
					oks.setSilent(true);
					// 指定分享平台，和slient一起使用可以直接分享到指定的平台
					//if (platform != null) {
					//        oks.setPlatform(platform);
					//}
					// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
					// oks.setCallback(new OneKeyShareCallback());
					//通过OneKeyShareCallback来修改不同平台分享的内容
					//oks.setShareContentCustomizeCallback(
					//new ShareContentCustomizeDemo());
	
					oks.show(HMBMainActivity.this);
				}catch (Exception e)
				{
					e.printStackTrace();
					Log.e(TAG,e.toString());
				}
				/* */
			}
		});
		
		startService(new Intent(this, HealthService.class));
	}

	public static void refreshImage()
	{
		if (myimageadapter!=null)
			myimageadapter.refresh();
	}
	//@Override
	//public void onResume (){
	//	super.onResume();		
	//	gridView.invalidateViews();
	//}
	private void deleteOnePerson(String personID) {

		String username = PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this);
		
		BasicCommCallback ccb = new BasicCommCallback();
		RemovePersonProfileTask task = new RemovePersonProfileTask(
				username, 
				personID, HMBMainActivity.this, ccb);
		HealthThreadPool.getInstance().execute(task);
		
		// user to person-------------------------------------
		try {
			Dao<UserToPersons, Integer> utop = getHelper(HMBMainActivity.this)
					.getUserToPersonsDao();
			DeleteBuilder<UserToPersons, Integer> deleteBuilder =

			utop.deleteBuilder();
			// only delete the rows where password is null
			deleteBuilder.where().eq("username", username).and()
				.eq("personID", personID);
			deleteBuilder.delete();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// person profile-------------------------------------
		try {

			Dao<PersonProfile, Integer> ppdao = getHelper(HMBMainActivity.this)
					.getPersonProfileDao();
			DeleteBuilder<PersonProfile, Integer> deleteBuilder =

			ppdao.deleteBuilder();
			// only delete the rows where password is null
			deleteBuilder.where().eq("personID", personID);
			deleteBuilder.delete();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// input data-------------------------------------
		try {

			Dao<HealthInputData, Integer> inputdao = getHelper(HMBMainActivity.this)
					.getInputDataDao();
			DeleteBuilder<HealthInputData, Integer> deleteBuilder =

			inputdao.deleteBuilder();
			// only delete the rows where password is null
			deleteBuilder.where().eq("personID", personID);
			deleteBuilder.delete();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// doctor suggestions-------------------------------------
		try {

			Dao<DoctorAndSuggestion, Integer> docdao = getHelper(HMBMainActivity.this)
					.getDoctorSuggestionDao();
			DeleteBuilder<DoctorAndSuggestion, Integer> deleteBuilder =

			docdao.deleteBuilder();
			// only delete the rows where password is null
			deleteBuilder.where().eq("personID", personID);
			deleteBuilder.delete();

			myimageadapter.loadData(true);
			gridView.invalidateViews();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus)
		{
			//setupView();
			// update grid view 
			myimageadapter.loadData(false);
			gridView.invalidateViews();
		}
	}

	class MyDialogListener implements DialogInterface.OnClickListener 
	{
		View view;
		String createType;
		public MyDialogListener(View view,String createType)
		{
			this.view = view;
			this.createType = createType;
		}
        public void onClick(DialogInterface dialog, int whichButton) {

			ProfileImageView pImageView = (ProfileImageView) view;
			final Intent intent = new Intent(HMBMainActivity.this, ViewPagerActivity.class);
			intent.putExtra(ConstantData.HMBPERSONID, pImageView.getPersonid());
			intent.putExtra("createType", createType);
			HMBMainActivity.this.startActivity(intent);
        	//setResult(RESULT_OK);//确定按钮事件
        	//finish();
        }
	}
	
	public void onClickShare() {
		DialogBuilder dbuilder = 
				new DialogBuilder(HMBMainActivity.this)
		.setTitle("分享")
		.setCustomizedContent("分享","取消" , R.layout.dialog_item_textinput,
				new DialogBuilder.OnDialogButtonClickListener() {
					
					@Override
					public void onDialogButtonClick(Context context, DialogBuilder builder,
							Dialog dialog, int dialogId, int which) {
						if (which == BUTTON_LEFT)
						{
							EditText edit = 
									(EditText) dialog.findViewById(R.id.dialogQuestion);
							String sharecode = edit.getText().toString();
							if ((sharecode!=null)&&(sharecode.length()>0))
							{								
								shareItByCode(sharecode);										
							}								
						}
						
					}
				});
		TextView title = (TextView) dbuilder.getDialog().findViewById(R.id.inputtextTitle);
		EditText edit = 
				(EditText) dbuilder.getDialog().findViewById(R.id.dialogQuestion);
		edit.setWidth(120);
		title.setText("分享码：");
		dbuilder.create()
		.show();
	};
	
	private void shareItByCode(String sharecode ) {

		BasicCommCallback ccb = new BasicCommCallback();
		
		ShareByInviteCodeTask sptask = new ShareByInviteCodeTask(
				HMBMainActivity.this,
				ccb,
				PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this), 
				sharecode);		
		HealthThreadPool.getInstance().execute(sptask);
		
		String sharepersonID = "";
		int i=0;
		ServerResponseCode src = ccb.getCommResult(ShareByInviteCodeTask.class, sharepersonID);
		while ((src==ServerResponseCode.WAITING) && (i<100))
		{
			synchronized (ccb) {
				try {
					ccb.wait(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			src = ccb.getCommResult(ShareByInviteCodeTask.class, sharepersonID);
			i++;
		}
		
		if (src==ServerResponseCode.SUCCESS)
		{
			sharepersonID = ccb.getResultValue();
			Toast.makeText(getApplicationContext(),
					"分享成功",
					Toast.LENGTH_SHORT).show();
		}else
		{
			Toast.makeText(getApplicationContext(),
				"分享失败",
				Toast.LENGTH_SHORT).show();
			return;
		}
		
		//------------------------------------------------------
		//update share list
		//------------------------------------------------------
		UserToPersonsDownloadTask updtask = new UserToPersonsDownloadTask(
				PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this),
				HMBMainActivity.this,
				ccb);
		
		HealthThreadPool.getInstance().execute(updtask);
		String responseValue = "";
		i=0;
		src = ccb.getCommResult(UserToPersonsDownloadTask.class, responseValue);
		while ((src==ServerResponseCode.WAITING) && (i<200))
		{
			synchronized (ccb) {
				try {
					ccb.wait(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			src = ccb.getCommResult(UserToPersonsDownloadTask.class, responseValue);
			i++;
		}
		if (src==ServerResponseCode.SUCCESS)
		{
			SyncUtility.syncPersonAll(sharepersonID, HMBMainActivity.this);
			//updateshareList();
		}else
		{
			Toast.makeText(getApplicationContext(),
					"更新分享列表失败",
					Toast.LENGTH_SHORT).show();			
		}
				
		
		
		return;
		
	}
	
//	private void shareIt(String sharecode ) {
//		
//		if (m_personid.equals(PersonProfileCache.getInstance(HMBMainActivity.this).getPersonID(HMBMainActivity.this)))
//		{
//			Toast.makeText(getApplicationContext(),
//					"别人不能取代自己，请为他建立一个单独的头像！",
//					Toast.LENGTH_SHORT).show();
//		}
//		
//		BasicCommCallback ccb = new BasicCommCallback();
//		
//		SharePersonTask sptask = new SharePersonTask(
//				PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this), 
//				m_personid, 
//				sharecode, 
//				HMBMainActivity.this, 
//				ccb);		
//		HealthThreadPool.getInstance().execute(sptask);
//		
//		String responseValue = "";
//		int i=0;
//		ServerResponseCode src = ccb.getCommResult(SharePersonTask.class, responseValue);
//		while ((src==ServerResponseCode.WAITING) && (i<100))
//		{
//			synchronized (ccb) {
//				try {
//					ccb.wait(100);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
//			src = ccb.getCommResult(SharePersonTask.class, responseValue);
//			i++;
//		}
//		
//		if (src==ServerResponseCode.SUCCESS)
//		{
//
//			Toast.makeText(getApplicationContext(),
//					"分享成功",
//					Toast.LENGTH_SHORT).show();
//		}else
//		{
//			Toast.makeText(getApplicationContext(),
//				"分享失败",
//				Toast.LENGTH_SHORT).show();
//			return;
//		}
//		
//		//------------------------------------------------------
//		//update share list
//		//------------------------------------------------------
//		UserToPersonsDownloadTask updtask = new UserToPersonsDownloadTask(
//				PersonProfileCache.getInstance(HMBMainActivity.this).getUsername(HMBMainActivity.this),
//				HMBMainActivity.this,
//				ccb);
//		
//		HealthThreadPool.getInstance().execute(updtask);
//		
//		i=0;
//		src = ccb.getCommResult(UserToPersonsDownloadTask.class, responseValue);
//		while ((src==ServerResponseCode.WAITING) && (i<20))
//		{
//			synchronized (ccb) {
//				try {
//					ccb.wait(100);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
//			src = ccb.getCommResult(UserToPersonsDownloadTask.class, responseValue);
//			i++;
//		}
//		if (src==ServerResponseCode.SUCCESS)
//		{
//			refreshImage();
//		}else
//		{
//			Toast.makeText(getApplicationContext(),
//					"更新分享列表失败",
//					Toast.LENGTH_SHORT).show();			
//		}
//	}
	
	private void setupView() {
		gridView = (GridView) findViewById(R.id.main_gridView);		
		
		gridView.setAdapter(myimageadapter);
		
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				final ProfileImageView pImageView = (ProfileImageView) view;
				if (!pImageView.getPersonid().equalsIgnoreCase(ConstantData.ADD_PERSON))				
				{
					new DialogBuilder(HMBMainActivity.this)
					.setTitle("提示")
					.setMessage("删除此用户?")
					.setButtons("确定","取消", new DialogBuilder.OnDialogButtonClickListener() {
						@Override
						public void onDialogButtonClick(Context context, DialogBuilder builder, Dialog dialog, int dialogId, int which) {
							if (which == BUTTON_LEFT) {
								deleteOnePerson(pImageView.getPersonid());
								HMBMainActivity.this.onWindowFocusChanged(true);
								Toast.makeText(HMBMainActivity.this, "", 0).show();//��˾��ʾ
							}
						}
						
					}).create().show(); 
					
//					new AlertDialog.Builder(HMBMainActivity.this)
//			        .setTitle("提示")
//			        .setMessage("删除此用户?")
//			        .setIcon(R.drawable.one)
//			        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//						
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							
//							deleteOnePerson(pImageView.getPersonid());
//							HMBMainActivity.this.onWindowFocusChanged(true);
//						}
//	
//						
//					})				
//			        .setNegativeButton("取消",  new DialogInterface.OnClickListener() {
//						
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							
//						}
//	
//					})				
//			        .show();
				}
				return true;
			}
		});
		//
		gridView.setOnItemClickListener(new OnItemClickListener() {

			/*
			 * get which image clicked
			 * */
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {
				ProfileImageView pImageView = (ProfileImageView) view;
				if (pImageView.getPersonid().equalsIgnoreCase(ConstantData.DOWNLOADING_PERSON))
				{
					Toast.makeText(HMBMainActivity.this, "下载中，请稍后", Toast.LENGTH_SHORT).show();
					//refresh the UI
					myimageadapter.loadData(true);
					gridView.invalidateViews();
					return;
				}
				if (pImageView.getPersonid().equalsIgnoreCase(ConstantData.ADD_PERSON))				
				{
					new DialogBuilder(HMBMainActivity.this)
					.setTitle("提示")
					.setMessage("创建新用户?")
					.setButtons("输入分享码","替她/他管理", new DialogBuilder.OnDialogButtonClickListener() {
						@Override
						public void onDialogButtonClick(Context context, DialogBuilder builder, Dialog dialog, int dialogId, int which) {
							if (which == BUTTON_LEFT) {
								onClickShare();
								//new MyDialogListener(view,"share").onClick(dialog, which);
								Toast.makeText(HMBMainActivity.this, "获取", Toast.LENGTH_SHORT).show();//
							}else if (which == BUTTON_RIGHT)
							{
								new MyDialogListener(view,"totalnew").onClick(dialog, which);
							}
						}
						
					}).create().show(); 

//					new AlertDialog.Builder(HMBMainActivity.this)
//			        .setTitle("提示")
//			        .setMessage("创建新用户?")
//			        .setIcon(R.drawable.one)
//			        .setPositiveButton("邀请家人朋友", new MyDialogListener(view,"share"))				
//			        .setNegativeButton("替她/他管理", new MyDialogListener(view,"totalnew"))
//			        .show();
				}else
				{
					if (fastUImode)
					{
						final Intent intent2 = new Intent(HMBMainActivity.this, FastUIActivity.class);
						intent2.putExtra(ConstantData.HMBPERSONID, pImageView.getPersonid());
						HMBMainActivity.this.startActivity(intent2);
						return;
					}
					final Intent intent = new Intent(HMBMainActivity.this, ViewPagerActivity.class);
					intent.putExtra(ConstantData.HMBPERSONID, pImageView.getPersonid());
					HMBMainActivity.this.startActivity(intent);
				}
				
			}
		});
	}
	
	@Override  
	public boolean onCreateOptionsMenu(Menu menu) {  
	    menu.add(0, 101, menu.size()+1, "添加关注人");  
	    return super.onCreateOptionsMenu(menu);  
	}  
	
	@Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        switch (item.getItemId()) {  
        case 101:  
        	final Intent intent = new Intent(this, ProfileActivity.class);
        	intent.setClass(HMBMainActivity.this, ProfileActivity.class);        	
			startActivity(intent);//
            break;  
        }  
        return super.onOptionsItemSelected(item,this);  
    }

	private long exitTime = 0;
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_BACK) {
	    	exit();
            return false;
	    }
		return super.onKeyDown(keyCode, event);
	}
	
	public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
        	finish();
        	super.stopApp();
        }
    }
	
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}  
	
}
